<?php
/***************************************************************************
 *							  functions_thumbs.php
 *							  -------------------
 *	 begin				  : Sat, Jul 27, 2002
 *	 copyright			  : (C) 2002 Meik Sievertsen
 *	 email				  : acyd.burn@gmx.de
 *
 ***************************************************************************/

/***************************************************************************
 *
 *	 This program is free software; you can redistribute it and/or modify
 *	 it under the terms of the GNU General Public License as published by
 *	 the Free Software Foundation; either version 2 of the License, or
 *	 (at your option) any later version.
 *
 *
 ***************************************************************************/

if (!defined('IN_PHPBB')) {
	die('Hacking attempt');
}

function create_thumbnail($source, $new_file)
{
	global $attach_config;
	$source = amod_realpath($source);
	$min_filesize = intval($attach_config['img_min_thumb_filesize']);
	$img_filesize = (file_exists(amod_realpath($source))) ? filesize($source) : false;
	if (!$img_filesize || $img_filesize <= $min_filesize) { return FALSE; }

	try
	{
		$img = \Poodle\Image::open($source);
		if ($img->getImageWidth() <= 0 || $img->getImageHeight() <= 0) { return false; }

		$tmp_path = '';
		$old_file = '';

		if (intval($attach_config['allow_ftp_upload'])) {
			$old_file = $new_file;
			$tmp_path = explode('/', $source);
			$tmp_path[count($tmp_path)-1] = '';
			$tmp_path = implode('/', $tmp_path);
			if ($tmp_path == '') { $tmp_path = '/tmp'; }
			$value = trim($tmp_path);
			if ($value[strlen($value)-1] == '/') { $value[strlen($value)-1] = ' '; }
			$new_file = trim($value) . '/t00000';
		}

		$img->thumbnailImage(400, 200, true);
		$img->writeImage($new_file);
		$new_file = $img->getImageFilename();

		if (!file_exists(amod_realpath($new_file))) { return FALSE; }

		if (intval($attach_config['allow_ftp_upload'])) {
			$result = ftp_file($new_file, $old_file, $this->type, TRUE); // True for disable error-mode
			if (!$result) { return FALSE; }
		} else {
			chmod($new_file, (PHP::$asNobody ? 0666 : 0644));
		}

		return TRUE;
	}
	catch (Exception $e) {}

	return false;
}
